package net.isocron.jiminy;

import java.util.List;

import net.isocron.jiminy.api.Statusnet;
import net.isocron.jiminy.api.Statusnet.Status;
import net.isocron.jiminy.db.AccountsDbAdapter;

import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;

/**
 * This is a very early proof of concept. 
 * I'm too lazy to copypaste the entire GPLv3 notice, 
 * Let this be the notice that says that the entire project is GPLv3. 
 * 
 * @author Nushio
 */

public class Jiminy  extends TabActivity {
	private final String MY_DEBUG_TAG = "Jiminy";
	AccountsDbAdapter mDbHelper;
	private Statusnet account;
	private static TabHost mTabHost;
	private String username="";
	private String password="";
//	private TextView tv; 
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mDbHelper = new AccountsDbAdapter(this);
        mDbHelper.open();
		Cursor accountsCursor = mDbHelper.fetchAccount(1);
		startManagingCursor(accountsCursor);
		try{
			if(account==null){
				username = accountsCursor.getString(accountsCursor.getColumnIndexOrThrow(AccountsDbAdapter.KEY_USERNAME));
				password = accountsCursor.getString(accountsCursor.getColumnIndexOrThrow(AccountsDbAdapter.KEY_PASSWORD));
				account = new Statusnet(username,password);
			}
		}catch(Exception e){
			startActivityForResult(new Intent(Jiminy.this, Login.class), 1);
		}
	    
		mTabHost = getTabHost();
		mTabHost.addTab(mTabHost.newTabSpec("tab_test1").setIndicator("Public Timeline").setContent(R.id.linear1));
        
		mTabHost.addTab(mTabHost.newTabSpec("tab_test2").setIndicator("My Timeline").setContent(R.id.linear2));    
		
		mTabHost.addTab(mTabHost.newTabSpec("tab_test3").setIndicator("My Replies").setContent(R.id.linear3));
		
		mTabHost.setCurrentTab(0);
		publicTimeline();
		myTimeline();
        myReplies();
        
		Button sendButton = (Button)findViewById(R.id.sendbutton); 
		if(sendButton != null){
			sendButton.setOnClickListener(new OnClickListener(){
               @Override
               public void onClick(View viewParam) {
                    // Create an 'empty' Intent
                    Intent myIntent = null;
                    // Find the NoticeBox(where the user can type),
                    // that we defined in the main.xml
                    EditText noticeBox = (EditText)findViewById(R.id.noticebox);
                    if(noticeBox == null){
                    	createDialog("Uhm, Dude...", "You must type something!");
                    }else{
                    	// Read out what the user typed into the NoticeBox
                    	String notice = noticeBox.getText().toString();
                    	if(notice.length() == 0){
                    		createDialog("Uhm, Dude...", "You must type something!");
                    		// For extreme usability, we set the Focus back to the noticeBox.
                    		// so the user can type again immediately.
                    		noticeBox.requestFocus();
                    	}else{
                    		account = new Statusnet(username, password);
                    		account.setSource("Jiminy");
                    		account.setStatus(notice);
                    		noticeBox.setText("");
                    		myTimeline();
                    	}
                    }
                    
                    // Start the activity if one was created
                    if(myIntent != null)
                         startActivity(myIntent);
               }
             });
         } 
		restoreMe();
	}		
	
	@Override 
	protected void onSaveInstanceState(Bundle outState) { 
		super.onSaveInstanceState(outState); 
	}
	
    private void startup(Intent i) {
        
        username = i.getStringExtra("userid");
        password = i.getStringExtra("password");

        myTimeline();
        myReplies();
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1 && resultCode == RESULT_CANCELED)
            finish();
        else
            startup(data);
    } 	
    
    @Override
    public Object onRetainNonConfigurationInstance() {
    	return(account);
    }
    
    private void restoreMe() {
    	account=null;
    	if (getLastNonConfigurationInstance()!=null) {
    		account=(Statusnet)getLastNonConfigurationInstance();
    	}
    }
    private void publicTimeline(){
	    String timeline = "Public Timeline";
		try {
			
			List<Status> lstatus = account.getPublicTimeline();
			for(int i=0;i<lstatus.size();i++){
				timeline+="\n"+lstatus.get(i).getUser().getName()+": "+lstatus.get(i).getText()+"\n";
			}
		} catch (Exception e) {
			/* Display any Error to the GUI. */
			timeline="Error: " + e.getMessage();
			Log.e(MY_DEBUG_TAG, "JiminyError", e);
		}
		TextView myTextView = (TextView) findViewById(R.id.textview1);        
	    myTextView.setText(timeline); 
    }
    
    private void myTimeline(){
    	String MyLine = username+" & Friends";
		try {
			if(account==null)
				account = new Statusnet(username,password);
			List<Status> lstatus = account.getFriendsTimeline();
			for(int i=0;i<lstatus.size();i++){
				MyLine+="\n"+lstatus.get(i).getUser().getName()+": "+lstatus.get(i).getText()+"\n";
			}
		} catch (Exception e) {
			/* Display any Error to the GUI. */
			Log.e(MY_DEBUG_TAG, "JiminyError", e);
		}
		TextView textView = (TextView) findViewById(R.id.textview2);        
        textView.setText(MyLine);
    }
    
    private void myReplies(){
    	String MyReplies = username+"'s Replies";
		try {
			if(account==null)
				account = new Statusnet(username,password);
			List<Status> lstatus = account.getReplies();
			for(int i=0;i<lstatus.size();i++){
				MyReplies+="\n"+lstatus.get(i).getUser().getName()+": "+lstatus.get(i).getText()+"\n";
			}
		} catch (Exception e) {
			/* Display any Error to the GUI. */
			Log.e(MY_DEBUG_TAG, "JiminyError", e);
		}
		TextView textView2 = (TextView) findViewById(R.id.textview3);        
        textView2.setText(MyReplies);
    }

	public Statusnet getAccount() {
		return account;
	}
	public void setAccount(Statusnet account) {
		this.account = account;
	}
    private void createDialog(String title, String text) {
        AlertDialog ad = new AlertDialog.Builder(this)
        .setPositiveButton("Ok, I get it.", null)
        .setTitle(title)
        .setMessage(text)
        .create();
        ad.show();
    } 
}
